<template>
  <!-- 整体容器，添加v-loading属性 -->
  <div class="data-list-container" v-loading="loading">
    <!-- 顶部搜索 + 工具栏 -->
    <div class="search-toolbar">
      <div>
        <el-input
          v-model="keyword"
          placeholder="请输入数据名称"
          clearable
          @keyup.enter="fetchData"
          @clear="handleClear"
        >
          <template #append>
            <div class="search-button" @click="fetchData">
              <img src="@/assets/imgs/home/search.png" />
              <span>搜索</span>
            </div>
          </template>
        </el-input>
      </div>

      <!-- <div class="tools">
        <el-button type="primary" :icon="Plus" @click="handleAdd">目录下载</el-button>
      </div> -->
    </div>
    <!-- 结果提示 -->
    <div class="result-sort-container">
      <div class="result-count">
        共有<span class="result-count-number">
          {{ total }}
        </span>
        个结果
      </div>
      <!-- <div class="sort-options">
        <div
          v-for="option in sortOptions"
          :key="option.field"
          class="sort-option"
          :class="{ active: sortField === option.field }"
          @click="handleSort(option.field)"
        >
          <span>{{ option.label }}</span>
          <div class="sort-arrows">
            <el-icon :class="{ active: sortField === option.field && sortOrder === 'asc' }">
              <ArrowUp />
            </el-icon>
            <el-icon :class="{ active: sortField === option.field && sortOrder === 'desc' }">
              <ArrowDown />
            </el-icon>
          </div>
        </div>
      </div> -->
    </div>

    <!-- 卡片列表  -->
    <div class="data-cards-container">
      <template v-if="cardList.length > 0">
        <div
          v-for="item in cardList"
          :key="item.catalogId"
          class="data-card-item"
          @click="handlePreview(item)"
        >
          <!-- 标题行 -->
          <div class="card-header">
            <div class="card-header-content">
              <span class="card-type">{{
                props.pageType === 'directory'
                  ? '目录'
                  : props.pageType === 'interface'
                    ? '接口'
                    : '数据集'
              }}</span>
              <span v-if="props.pageType !== 'interface'" class="card-title">{{
                item.catalogName
              }}</span>
              <span v-if="props.pageType === 'interface'" class="card-title"
                >{{ item.catalogName }} ({{ item.interfaceName }})</span
              >
            </div>

            <div class="card-actions">
              <el-button link :icon="View">数据预览</el-button>
              <el-button
                link
                :icon="Star"
                :type="item.collected == '1' ? 'warning' : 'info'"
                @click.stop="toggleCollect(item)"
                class="collect-button"
              >
                <span class="collect-text">
                  {{ item.collected == '1' ? '已收藏' : '收藏' }}
                </span>
              </el-button>
            </div>
          </div>

          <!-- 标签 -->
          <div class="card-tags">
            <el-tag
              style="background: #fdf6ec"
              size="small"
              :type="getShareTypeTagType(item.shareProperty)"
            >
              {{ getShareTypeLabel(item.shareProperty) }}
            </el-tag>
            <el-tag style="background: #ecf5ff; margin-left: 6px" size="small">{{
              item.irCode
            }}</el-tag>
            <el-tag
              v-if="props.pageType === 'dataset'"
              type="danger"
              style="background: #fdf6ec; margin-left: 6px"
              size="small"
              >XML</el-tag
            >
            <el-tag
              v-if="props.pageType === 'dataset'"
              type="success"
              style="background: #f6fdfc; margin-left: 6px"
              size="small"
              >CSV</el-tag
            >
            <el-tag
              v-if="props.pageType === 'dataset'"
              type="warning"
              style="background: #ecf5ff; margin-left: 6px"
              size="small"
              >XLS</el-tag
            >
            <el-tag
              v-if="props.pageType === 'interface'"
              type="warning"
              style="background: #ecf5ff; margin-left: 6px"
              size="small"
              >{{ item.interfaceMethod == '1' ? 'POST' : 'GET' }}</el-tag
            >
          </div>

          <!-- 摘要 -->
          <!-- <div class="card-summary">{{ item.catalogName }}</div> -->

          <!-- 底部信息 -->
          <div class="card-footer">
            <div class="info-item">
              <img src="@/assets/imgs/data/data-unit.png" />
              <span>提供方：{{ item.deptName }}</span>
            </div>
            <div class="info-item">
              <img src="@/assets/imgs/data/view.png" />
              <span>查看：{{ item.viewNum }}次</span>
            </div>
            <div class="info-item">
              <img src="@/assets/imgs/data/time.png" />
              <span>更新时间：{{ item.updateTime }}</span>
            </div>
          </div>
        </div>
      </template>
      <el-empty v-else-if="!loading" description="暂无数据" :image-size="200" />
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 40, 80]"
        layout="total,sizes, prev, pager, next, jumper"
        @current-change="fetchData"
        @size-change="fetchData"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { View, Star, ArrowDown, ArrowUp } from '@element-plus/icons-vue'
import * as PortalApi from '@/api/portal'
import { useSearchStore } from '@/store/modules/search'
import { spawn } from 'child_process'

// 定义字典数据类型
interface DictItem {
  value: string
  label: string
  colorType?: string
  cssClass?: string
}

// interface ApiResponse {
//   total: number
//   msg: string
// }

// 定义组件属性，接收页面类型参数
const props = defineProps<{
  pageType: 'directory' | 'interface' | 'dataset'
  menuId: any
  filterParams?: Record<string, string> // 新增筛选参数
}>()
const searchStore = useSearchStore()

const keyword = ref('')
const loading = ref(false)
const cardList: any = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const router = useRouter()
const shareTypeDict = ref<DictItem[]>([])

// 监听menuId和筛选参数变化
watch(
  () => [props.menuId, props.filterParams],
  () => {
    if (
      props.pageType === 'directory' ||
      props.pageType === 'interface' ||
      props.pageType === 'dataset'
    ) {
      // 在数据目录页面和数据接口页面都重新获取数据
      fetchData()
    }
  },
  { immediate: false, deep: true }
)

// 获取shareType字典数据
const fetchShareTypeDict = async () => {
  try {
    const response = await PortalApi.getDictByCode({ dictType: 'shareProperty' })
    shareTypeDict.value = response || []
  } catch (error) {
    console.error('获取shareType字典数据失败:', error)
    // 如果接口调用失败，使用默认数据
    shareTypeDict.value = [
      { value: '1', label: '无条件共享' },
      { value: '2', label: '有条件共享' },
      { value: '3', label: '不予共享' }
    ]
  }
}

// 根据shareProperty值获取对应的标签文本
const getShareTypeLabel = (shareProperty: string) => {
  const dictItem = shareTypeDict.value.find((item) => item.value === shareProperty)
  return dictItem ? dictItem.label : '未知共享类型'
}

// 根据shareProperty值获取对应的标签类型
const getShareTypeTagType = (shareProperty: string) => {
  switch (shareProperty) {
    case '1':
      return 'success'
    case '2':
      return 'warning'
    case '3':
      return 'info'
    default:
      return 'info'
  }
}

// 处理搜索框清空事件
const handleClear = () => {
  currentPage.value = 1
  // searchStore.clearKeyword()
  fetchData()
}

// 调用接口获取数据
const fetchData = async () => {
  loading.value = true

  // 清空数据
  cardList.value = []

  try {
    // 根据页面类型调用不同的API
    if (props.pageType === 'directory' || props.pageType === 'dataset') {
      // 构建查询参数
      const queryParams: any = {
        pageNo: currentPage.value,
        pageSize: pageSize.value
      }

      // 添加menuId参数
      if (props.menuId) {
        queryParams.menuId = props.menuId
      }

      // 添加筛选参数
      if (props.filterParams) {
        Object.assign(queryParams, props.filterParams)
      }

      // 添加搜索关键词
      if (keyword.value) {
        queryParams.catalogName = keyword.value
      }

      const response = await PortalApi.getResourceDirectoryPage(queryParams)
      total.value = response.total || 0
      cardList.value = response.list || []
    } else if (props.pageType === 'interface') {
      // 数据接口页面调用对应接口
      const queryParams: any = {
        pageNo: currentPage.value,
        pageSize: pageSize.value
      }

      // 添加menuId参数
      if (props.menuId) {
        queryParams.menuId = props.menuId
      }

      // 添加筛选参数
      if (props.filterParams) {
        Object.assign(queryParams, props.filterParams)
      }

      // 添加搜索关键词
      if (keyword.value) {
        queryParams.catalogName = keyword.value
      }

      const response = await PortalApi.getInterfaceList(queryParams)

      total.value = response.total || 0
      cardList.value = response.list || []
    } else {
      total.value = 0
      cardList.value = []
    }

    // // 如果有排序条件，应用排序
    // if (sortField.value) {
    //   applySorting()
    // }
  } catch (error) {
    console.error('获取数据列表失败:', error)
    // 错误处理，可以添加提示信息
  } finally {
    loading.value = false
  }
}

const handlePreview = (item: any) => {
  // 跳转到详情页面
  router.push({
    name: 'DataDetail',
    params: { id: item.catalogId }
  })
}

// 修改toggleCollect函数，添加API调用
const toggleCollect = async (item: any) => {
  try {
    // 调用收藏接口
    const response = await PortalApi.getCollect(item.catalogId)

    if (response) {
      await fetchData()

      ElMessage.success(item.collected == 1 ? '取消收藏成功' : '收藏成功')
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    // ElMessage.error(error.message || '收藏操作失败')
  }
}
// const handleAdd = () => console.log('目录下载')

// 排序相关变量
const sortField = ref<string>('')
const sortOrder = ref<'asc' | 'desc'>('asc')

const sortOptions = [
  { field: 'updateTime', label: '更新时间' },
  { field: 'viewNum', label: '访问量' }
]

// 排序处理函数
const handleSort = (field: string) => {
  if (sortField.value === field) {
    // 同一字段点击切换排序方向
    sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc'
  } else {
    // 不同字段点击，默认升序
    sortField.value = field
    sortOrder.value = 'asc'
  }
  // applySorting()
}

// 应用排序
// const applySorting = () => {
//   if (!sortField.value) return

//   cardList.value.sort((a, b) => {
//     let valueA = a[sortField.value as keyof CardItem]
//     let valueB = b[sortField.value as keyof CardItem]

//     // 特殊处理不同数据类型的排序
//     if (sortField.value === 'viewNum') {
//       // 访问量需要去除千分位逗号再比较
//       valueA = Number(String(valueA).replace(/[^0-9]/g, ''))
//       valueB = Number(String(valueB).replace(/[^0-9]/g, ''))
//     } else if (sortField.value === 'updateTime') {
//       // 更新时间转换为时间戳比较
//       valueA = new Date(valueA as string).getTime()
//       valueB = new Date(valueB as string).getTime()
//     }

//     if (sortOrder.value === 'asc') {
//       return valueA > valueB ? 1 : -1
//     } else {
//       return valueA < valueB ? 1 : -1
//     }
//   })
// }

// if (searchStore.keyword) {
//   nextTick(() => {
//     keyword.value = searchStore.keyword
//     currentPage.value = 1
//     PortalApi.getResourceDirectoryPage(keyword.value)
//   })
// }

// 添加对searchStore中keyword变化的监听
watch(
  () => searchStore.keyword,
  (newKeyword) => {
    if (newKeyword) {
      keyword.value = newKeyword
      currentPage.value = 1
      fetchData()
    } else {
      // 如果关键词被清空，也清空本地搜索框
      keyword.value = ''
      currentPage.value = 1
      fetchData()
    }
  },
  { immediate: true, deep: true }
)

onMounted(() => {
  fetchData()

  fetchShareTypeDict()
})
</script>

<style scoped lang="scss">
.data-list-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 16px;

  .search-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;

    :deep(.el-input__wrapper) {
      width: 450px;
      height: 50px;
    }

    :deep(.el-input-group__append) {
      width: 100px;
      background-color: #ffffff;
      padding: 2px;
    }

    :deep(.el-input-group__append) {
      width: 130px;
    }

    .search-button {
      cursor: pointer;
      margin: 0;
      width: 100%;
      height: 100%;
      padding: 0;
      background-color: #17a7ff;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #ffffff;

      img {
        width: 16px;
        height: 16px;
        margin-right: 8px;
      }
    }
  }

  .result-sort-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
  }

  .result-count {
    font-size: 14px;
    color: #999999;

    .result-count-number {
      font-size: 18px;
      color: #1faaff;
      margin: 0 8px;
    }
  }

  .sort-options {
    display: flex;
    align-items: center;
    gap: 20px;
  }

  .sort-option {
    display: flex;
    align-items: center;
    gap: 4px;
    cursor: pointer;
    padding: 6px 12px;
    border-radius: 4px;
    font-size: 14px;
    color: #606266;

    &:hover {
      background-color: #f5f7fa;
    }

    &.active {
      color: #409eff;
      background-color: #ecf5ff;
    }
  }

  .sort-arrows {
    display: flex;
    flex-direction: column;
    gap: 4px;

    .el-icon {
      font-size: 12px;
      color: #c0c4cc;

      &.active {
        color: #409eff;
      }
    }
  }

  .data-cards-container {
    flex: 1;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .data-card-item {
    background: #fff url('@/assets/imgs/data/back-data.png') no-repeat center center;
    background-size: cover;
    border-radius: 4px;
    padding: 16px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
    display: flex;
    flex-direction: column;
    position: relative;
    cursor: pointer;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;

      .card-header-content {
        display: flex;
        align-items: center;
        .card-type {
          color: #f6fcff;
          padding: 6px;
          background: #009eff;
          border-radius: 4px 4px 4px 4px;
          font-size: 12px;
          margin-right: 8px;
        }

        .card-title {
          font-size: 18px;
          font-weight: 500;
          color: #303133;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

      .card-actions {
        display: flex;
        align-items: center;
        gap: 8px;

        .el-button:first-child {
          min-width: 80px;
          width: 80px;
          justify-content: center;
        }

        .collect-button {
          min-width: 80px;
          width: 80px;
          justify-content: center;
          transition: all 0.3s ease;

          &:hover {
            transform: scale(1.05);
          }

          &:active {
            transform: scale(0.95);
          }

          .el-icon {
            transition:
              transform 0.3s ease,
              color 0.3s ease;
          }

          &:hover .el-icon {
            transform: scale(1.2);
          }
        }

        .collect-text {
          transition:
            color 0.3s ease,
            transform 0.3s ease;
          color: inherit;

          .collect-button:hover & {
            transform: translateX(2px);
          }
        }
      }
    }

    .card-tags {
      margin-bottom: 8px;
    }

    .card-summary {
      font-size: 14px;
      color: #606266;
      line-height: 1.6;
      margin-bottom: 12px;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }

    .card-footer {
      font-size: 13px;
      color: #909399;
      display: flex;
      gap: 50px;

      .info-item {
        display: flex;
        align-items: center;
        gap: 4px;

        img {
          width: 16px;
          height: 16px;
        }
      }
    }
  }

  .pagination-container {
    margin-top: 16px;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 12px;

    .page-size-selector {
      display: flex;
      align-items: center;
      font-size: 14px;
      color: #606266;
      cursor: pointer;
    }
  }
}
</style>
